﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using UCNKompetenceBors.Database;
using UCNKompetenceBors.Model;

namespace UCNKompetenceBors.Admin
{
    public partial class adminUsersEdit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                ckeditorEditUserBio.Width = 450;
                this.Form.DefaultButton = btnEditUserConfirm.UniqueID;

                lblConfirmUpdatedUser.Visible = false;

                BindRoleDropdown();
                BindSubMenu();
                BindData();    

                #region Globalization
                string culture = String.Empty;

                if (HttpContext.Current.Session["MyCulture"] != null)
                    culture = HttpContext.Current.Session["MyCulture"].ToString();

                if (!String.IsNullOrEmpty(culture))
                    GeneralTools.SetCulture(culture);

                LocalizeControls();
                #endregion
            }
        }

        /// <summary>
        /// Binds the sub menu links.
        /// </summary>
        private void BindSubMenu()
        {
            hyLinkAdminDashboard.NavigateUrl = "~/Admin/admin.aspx";
            hyLinkUserHandling.NavigateUrl = "~/Admin/adminUsers.aspx";
            hyLinkCreateUser.NavigateUrl = "~/Admin/adminUsersCreate.aspx";
            hyLinkAdminExchange.NavigateUrl = "~/Admin/adminExchange.aspx";
            hyLinkNewsHandling.NavigateUrl = "~/Admin/adminNews.aspx";
            hyLinkEditInformation.NavigateUrl = "~/Admin/adminInformation.aspx";
            hyLinkContactPerson.NavigateUrl = "~/Admin/adminContactPerson.aspx";
            hylinkDepartment.NavigateUrl = "~/Admin/adminDepartment.aspx";
            hyLinkResetUsers.NavigateUrl = "~/Admin/adminUsersReset.aspx";
        }

        /// <summary>
        /// Binds the controls with a user.
        /// </summary>
        private void BindData()
        {
            string uid = Request.QueryString["uid"];

            LoginUser user = dbAdmin.GetUserById(Guid.Parse(uid));

            if (user != null)
            {
                lblEditUserName.Text = user.UserName;
                txtEditUserEmail.Text = user.Email;
                txtEditUserFname.Text = user.FirstName;
                txtEditUserLname.Text = user.LastName;
                txtEditUserPhone.Text = user.Phone;
                ckeditorEditUserBio.Text = user.Biography;

                string[] roles = Roles.GetRolesForUser(user.UserName);

                if (roles.Length > 0)
                    ddlEditUserRole.SelectedValue = roles[0];
            }
            else
            {
                txtEditUserEmail.Enabled = false;
                txtEditUserFname.Enabled = false;
                txtEditUserLname.Enabled = false;
                txtEditUserPhone.Enabled = false;
                ckeditorEditUserBio.Enabled = false;
                ddlEditUserRole.Enabled = false;
                btnEditUserConfirm.Enabled = false;
            }
        }

        private void BindRoleDropdown()
        {
            ddlEditUserRole.Items.Clear();
            ddlEditUserRole.Items.Add(new ListItem(GetLocalResourceObject("ddlEditUserRoleText").ToString(), "Vælg Rolle"));
            ddlEditUserRole.Items.Add(new ListItem(GetLocalResourceObject("roleUserText").ToString(), "user"));
            ddlEditUserRole.Items.Add(new ListItem(GetLocalResourceObject("roleAdminText").ToString(), "administrator"));
        }

        protected void btnEditUserCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/adminUsers.aspx");
        }

        /// <summary>
        /// Edits a user, based on the input parameters.
        /// </summary>
        /// <param name="role">Specifies the role to be used.</param>
        /// <param name="email">Specifies the e-mail to be used.</param>
        /// <param name="firstName">Specifies the first name to be used.</param>
        /// <param name="lastName">Specifies the last name to be used.</param>
        /// <param name="phone">Specifies the phone to be used.</param>
        /// <param name="bio">Specifies the biography to be used.</param>
        /// <param name="userId">Specifies the ID of the user to be edited</param>
        private void UpdateInfo(string role, string email, string firstName, string lastName, string phone, string bio)
        {
            MembershipUser mu = Membership.GetUser(lblEditUserName.Text);

            if (!email.Equals(mu.Email))
            {
                mu.Email = email;

                Membership.UpdateUser(mu);
            }

            string[] roles = Roles.GetRolesForUser(mu.UserName);

            if (roles.Length > 0)
            {
                if (!role.Equals(roles[0]))
                {
                    Roles.RemoveUserFromRole(mu.UserName, roles[0]);
                    Roles.AddUserToRole(mu.UserName, role);
                }
            }           

            dbAdmin.EditUser(firstName, lastName, phone, bio, Guid.Parse(Request.QueryString["uid"].ToString()));
        }

        protected void btnEditUserConfirm_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                lblConfirmUpdatedUser.Visible = true;
                string role = ddlEditUserRole.SelectedValue;
                string email = txtEditUserEmail.Text;
                string fName = txtEditUserFname.Text;
                string lName = txtEditUserLname.Text;
                string phone = txtEditUserPhone.Text;
                string bio = ckeditorEditUserBio.Text;

                UpdateInfo(role, email, fName, lName, phone, bio);
            }            
        }

        /// <summary>
        /// Localizes the controls of the site, based on the current UI Culture.
        /// </summary>
        private void LocalizeControls()
        {
            hyLinkAdminDashboard.Text = GetLocalResourceObject("hyLinkAdminDashboardText").ToString();
            hyLinkUserHandling.Text = GetLocalResourceObject("hyLinkUserHandlingText").ToString();
            hyLinkAdminExchange.Text = GetLocalResourceObject("hyLinkAdminExchangeText").ToString();
            hyLinkNewsHandling.Text = GetLocalResourceObject("hyLinkNewsHandlingText").ToString();
            hyLinkEditInformation.Text = GetLocalResourceObject("hyLinkEditInformationText").ToString();
            hyLinkResetUsers.Text = GetLocalResourceObject("hyLinkResetUsersText").ToString();
            hyLinkContactPerson.Text = GetLocalResourceObject("hyLinkContactPersonText").ToString();
            hylinkDepartment.Text = GetLocalResourceObject("hylinkDepartmentText").ToString();
            hyLinkCreateUser.Text = GetLocalResourceObject("hyLinkCreateUserText").ToString();

            lblEditUserBio.Text = GetLocalResourceObject("lblEditUserBioText").ToString();
            lblAdminUsersEditHeader.Text = GetLocalResourceObject("lblAdminUsersEditHeaderText").ToString();
            lblEditUserEmail.Text = GetLocalResourceObject("lblEditUserEmailText").ToString();
            lblEditUserFname.Text = GetLocalResourceObject("lblEditUserFnameText").ToString();
            lblEditUserLname.Text = GetLocalResourceObject("lblEditUserLnameText").ToString();
            lblEditUserPhone.Text = GetLocalResourceObject("lblEditUserPhoneText").ToString();
            lblUserName.Text = GetLocalResourceObject("lblUserNameText").ToString();
            lblEditUserRole.Text = GetLocalResourceObject("lblEditUserRoleText").ToString();
            lblConfirmUpdatedUser.Text = GetLocalResourceObject("lblConfirmUpdatedUserText").ToString();

            string regexMailValidation = GetLocalResourceObject("regexvalEmailText").ToString();
            regexvalEmail.ToolTip = regexMailValidation;
            regexvalEmail.ErrorMessage = regexMailValidation;

            string phoneValidation = GetLocalResourceObject("regexvalPhoneText").ToString();
            regexvalPhone.ToolTip = phoneValidation;
            regexvalPhone.ErrorMessage = phoneValidation;

            string mailValidation = GetLocalResourceObject("rfvalEditUserEmailText").ToString();
            rfvalEditUserEmail.ToolTip = mailValidation;
            rfvalEditUserEmail.ErrorMessage = mailValidation;

            string fNameValidation = GetLocalResourceObject("rfvalEditUserFnameText").ToString();
            rfvalEditUserFname.ToolTip = fNameValidation;
            rfvalEditUserFname.ErrorMessage = fNameValidation;

            string lNameValidation = GetLocalResourceObject("rfvalEditUserLnameText").ToString();
            rfvalEditUserLname.ToolTip = lNameValidation;
            rfvalEditUserLname.ErrorMessage = lNameValidation;

            string userRoleValidation = GetLocalResourceObject("rfvalEditUserRoleText").ToString();
            rfvalEditUserRole.ToolTip = userRoleValidation;
            rfvalEditUserRole.ErrorMessage = userRoleValidation;

            valsumEditUser.HeaderText = GetLocalResourceObject("valsumEditUserText").ToString();

            btnEditUserCancel.Text = GetLocalResourceObject("btnEditUserCancelText").ToString();
            btnEditUserConfirm.Text = GetLocalResourceObject("btnEditUserConfirmText").ToString();

            string culture = String.Empty;

            if (HttpContext.Current.Session["MyCulture"] != null)
                culture = HttpContext.Current.Session["MyCulture"].ToString();

            if (culture.Equals("en-GB"))
                ckeditorEditUserBio.Language = "en";
            else
                ckeditorEditUserBio.Language = "da";

            BindRoleDropdown();
            BindData();
        }
    }
}